package com.ljf.intercepter;

import com.alibaba.fastjson.JSONObject;
import com.ljf.annotation.HasPermission;
import com.ljf.annotation.NoRequireLogin;
import com.ljf.constants.HttpStatus;
import com.ljf.entity.Employee;
import com.ljf.exception.BusinessException;
import com.ljf.redis.RedisKeys;
import com.ljf.redis.RedisTemplateService;
import com.ljf.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class EmpLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplateService redisTemplateService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute("employee");
        if (attribute!= null){
            return true;
        }
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        //获取token
        String token = request.getHeader("token");
        //是否有不用登录认证的注解
        HandlerMethod handler1 = (HandlerMethod) handler;
        NoRequireLogin noRequireLogin = handler1.getMethodAnnotation(NoRequireLogin.class);
        if (noRequireLogin != null){
            return true;
        }else {
            if (StringUtils.hasText(token)){
                String value2 = redisTemplateService.getCacheObject(token);
                if (!StringUtils.hasText(value2)){
                    Result res = Result.fail(HttpStatus.CODE_BUSINESS_ERROR, "请先登录");
                    String result = JSONObject.toJSONString(res);
                    response.getWriter().println(result);
                    response.getWriter().flush();
                    return false;
                }else {
                    //缓存中有值，就延长储存时间
                    redisTemplateService.expire(token, RedisKeys.LOGIN_USER.getTimeout(),RedisKeys.LOGIN_USER.getTimeUnit());

                }
            }else {
                //没有token的话
                Result res = Result.fail(HttpStatus.CODE_BUSINESS_ERROR, "请先登录");
                String result = JSONObject.toJSONString(res);
                response.getWriter().println(result);
                response.getWriter().flush();
                return false;
            }

        }
        //判断是否有HasPermission注解
        HandlerMethod handler2 = (HandlerMethod) handler;
        HasPermission hasPermission = handler2.getMethodAnnotation(HasPermission.class);
        if (hasPermission != null){
            if (!StringUtils.hasText(token)){
                //没有token
                Result res = Result.fail(HttpStatus.CODE_BUSINESS_ERROR, "请先登录");
                String result = JSONObject.toJSONString(res);
                response.getWriter().println(result);
                response.getWriter().flush();
                return false;
            }
            Employee employee = JSONObject.parseObject(redisTemplateService.getCacheObject(token), Employee.class);
            //判断是否是系统管理员
            if (employee.getIsAdmin()){
                //是，放行
                return true;
            }
            //不是
            String value = hasPermission.value();
            boolean contains = employee.getFlags().contains(value);
            if (!contains){
                Result res = Result.fail(HttpStatus.CODE_BUSINESS_ERROR, "您没有权限操作");
                String result = JSONObject.toJSONString(res);
                response.getWriter().println(result);
                response.getWriter().flush();
                return false;

            }
        }

       return true;
    }
}
